package com.service.impl;

import com.common.exception.db.InsertException;
import com.common.exception.db.UpdateException;
import com.dao.BillDao;
import com.dao.LoginDao;
import com.dao.ManageDao;
import com.dao.TranslationDao;
import com.dto.in.RegisterInfo;
import com.entity.LoginInfo;
import com.service.LoginService;
import com.util.UUIDUtil;
import net.sf.json.JSONArray;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Administrator on 2019/1/2 0002.
 */
@Service
public class LoginServiceImpl implements LoginService{
    @Autowired
    private LoginDao dao;
    @Autowired
    private ManageDao manageDao;
    @Autowired
    private TranslationDao translationDao;
    @Autowired
    private BillDao billDao;

    @Override
    public int findUserYou50() {
       int count = dao.deleteUserYou50();
       count = dao.deleteBillIsPhone();
        return 1;
    }

    @Override
    public int login(String wxNickName, String wxSex, String wxAvatar,String userType, String openId ,String newOpenId) {
        if(wxSex.equals("1")){
            wxSex = "男";
        }else{
            wxSex = "女";
        }
        if(openId.equals("") || openId.equals(null)){
            return 0;
        }
        int count = dao.findOpenId(openId);
        if(count == 1){
            count = dao.findUserId(openId);
            return count;
        }else if(count > 1) {
            return 0;
        }else{
            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setWxSex(wxSex);
            loginInfo.setWxNickName(wxNickName);
            loginInfo.setWxAvatar(wxAvatar);
            loginInfo.setUserType(userType);
            loginInfo.setOpenId(openId);
            loginInfo.setNewOpenId(newOpenId);
            count = dao.insertUser(loginInfo);
            if(count > 0){
                return loginInfo.getId();
            }else{
                return 0;
            }
        }
    }

    @Override
    public LoginInfo findUser(String openId) {
        return dao.findUser(openId);
    }

    @Override
    public Map findUserType(String openId) {
        String userType = dao.findUserType(openId);
        Map map = new HashMap();
        if(userType == null){
            map.put("userType","");
            map.put("userId",0);
        }else{
            int userId = dao.findUserId(openId);
            map.put("userType",userType);
            map.put("userId",userId);
        }
        return map;
    }


    public String findPhone(Integer userId) {
        return dao.findPhone(userId);
    }


    @Override
    @Transactional
    public int updatePhone(Integer userId, String phone,Integer type) {
        int count = dao.findPhoneIsNo(phone);
        if(count > 0){
            return -1;
        }else{
            count = dao.updatePhone(userId, phone);
            if(count > 0){
                return count;
            }else {
                throw new UpdateException("修改失败");
            }
        }
    }

    @Override
    public Map findUserMsg(Integer userId, Integer userId1) {
        LoginInfo user = dao.findUserMsg(userId);
        LoginInfo user1 = dao.findUserMsg(userId1);
        Map map = new HashMap();
        map.put("user",user);
        map.put("user1",user1);
        return map;
    }

    @Override
    public List<LoginInfo> findUserMsg1(String userId) {
        JSONArray userIds = JSONArray.fromObject(userId);
        List list = new ArrayList();
        for(int i =0; i < userIds.size(); i++){
            String id=String.valueOf(userIds.get(i));
            int b=Integer.parseInt(id);
            LoginInfo info = dao.findUserMsg(b);
            list.add(info);
        }
        return list;
    }

    @Override
    public LoginInfo findUserMsg2(Integer userId) {
        return dao.findUserMsg(userId);
    }

    @Override
    @Transactional
    public int newRegister(RegisterInfo registerInfo) {
        String randomNum = "";
        if(registerInfo.getType().equals("student")){
            for(;;){
                randomNum = randomHexString(6);
                int count = dao.findRandomNum(randomNum);
                if(count == 0){
                    break;
                }
            }
        }
        //查用户是否存在
        int counts = dao.findUserMessage(registerInfo.getUserId());
        if(counts > 0){
            return -1;
        }else{
            //如果邀请码不为空
            if(!registerInfo.getCode().equals("")){
                counts = dao.findRandomNum(registerInfo.getCode());
                if(counts > 0){
                    int pUserId = dao.findPuserId(registerInfo.getCode());
                    counts = translationDao.insertPromotionUser(registerInfo.getUserId(),pUserId,1);
                    if(counts > 0){
                        counts = dao.insertMoney(pUserId,new BigDecimal(20));
                        if(counts > 0){
                            String uuid = UUIDUtil.get32UUID();
                            counts = billDao.insertBill(pUserId,new BigDecimal(20),1,"推广奖励",uuid);
                            if(counts < 1){
                                throw new InsertException("新增流水失败");
                            }
                        }else{
                            throw new InsertException("新增对方金额失败");
                        }
                    }else{
                        throw new InsertException("新增用户父子关系表失败");
                    }
                }else{
                    return -2;
                }
            }
            return dao.newRegister(registerInfo,randomNum);
        }
    }

    @Override
    public int findRegisterIsBeing(Integer userId) {
        return dao.findUserMessage(userId);
    }

    @Override
    public int findRanCodeIsBeing(String code) {
        if(!code.equals("")){
            int counts = dao.findRandomNum(code);
            if(counts > 0){
                return 1;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }

    @Override
    public String findInvitationCode(Integer userId) {
        return dao.findInvitationCode(userId);
    }

    @Override
    public int findTimedTask() {
        return dao.findTimedTask();
    }

    @Override
    public List<LoginInfo> findUserAll() {
        return dao.findUserAll();
    }

    /**
     * 获取16进制随机数
     * @param len
     * @return
     * @throws
     */
    public static String randomHexString(int len) {
        try {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < len; i++) {
                result.append(Integer.toHexString(new Random().nextInt(16)));
            }
            return result.toString().toUpperCase();

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        }
        return null;
    }
}
